import numpy as np
import xlsxwriter
import sys
import pandas as p
from sfi import Scalar
import scipy.stats as stat
def calculateARStat(pi, delta, piVar, deltaVar, covar, nullLow, nullDelta, nullHigh, modelTitle):

    #Convert all values to numerics
    piVal = float(Scalar.getValue(str(pi)))
    deltaVal = float(Scalar.getValue(str(delta)))
    piVarVal = float(Scalar.getValue(str(piVar)))
    deltaVarVal = float(Scalar.getValue(str(deltaVar)))
    covarVal = float(Scalar.getValue(str(covar)))
    nullLowVal = float(nullLow)
    nullDeltaVal = float(nullDelta)
    nullHighVal = float(nullHigh)

    #Establish a range of values to test
    nullVals = np.arange(nullLowVal, nullHighVal, nullDeltaVal)

    #Append maximum value to test
    if(max(nullVals)<nullHighVal):
        nullVals = np.hstack((nullVals, np.array([nullHighVal])))


    #Calculate statistics and p-values
    numerator = np.power((deltaVal-np.multiply(piVal, nullVals)), 2)
    denominator = deltaVarVal+np.multiply(np.power(nullVals,2),piVarVal)-np.multiply(2*covarVal,nullVals)
    arStats = np.divide(numerator, denominator)
    pVals = 1-stat.chi2(1).cdf(arStats)

    #Save individual IV workbook
    workbookFile = 'Tables/iv-{}.xlsx'.format(modelTitle)
    if(not sys.platform=='darwin'):
        workbookFile = 'Tables\iv-{}.xlsx'.format(modelTitle)
    sheetTitle = 'NullValueTests'#str(modelTitle)

    #Write information
    nullCol = 0
    arCol = 1
    pValCol = 2

    wb = xlsxwriter.Workbook(workbookFile, {'nan_inf_to_errors': True})
    sheet = wb.add_worksheet(sheetTitle)

    sheet.write('A1', "Null Beta Value")
    sheet.write('B1', "AR-Statistic")
    sheet.write('C1', "P-Value")

    sheet.write_column(1, nullCol, nullVals)
    sheet.write_column(1, arCol, arStats)
    sheet.write_column(1, pValCol, pVals)

    #Close workbook
    wb.close()





def main():

    #Gather the arguments to calculate statistics
    pi = sys.argv[1]
    delta = sys.argv[2]
    piVar = sys.argv[3]
    deltaVar = sys.argv[4]
    covar = sys.argv[5]
    nullLow = sys.argv[6]
    nullDelta = sys.argv[7]
    nullHigh = sys.argv[8]
    modelTitle = sys.argv[9]
    #Calculate and store IV statistics
    calculateARStat(pi, delta, piVar, deltaVar, covar, nullLow, nullDelta, nullHigh, modelTitle)

if __name__=='__main__':
    #Run
    main()